package com.roc.web.action;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionContext;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.MerchantModuleRight;
import com.roc.pojo.Module;
import com.roc.pojo.OrgBean;
import com.roc.service.IMerchantServices;
import com.roc.service.IPagenitionService;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.util.Constance;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;

/**
 * 
 * @author 陈锴
 * 
 * 权限管理
 * 
 * 2014-05-27
 *
 */

@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/power")
public class PowerAction extends PaginationBaseAction{
	
	private Logger logger=LogManager.getLogger(PowerAction.class);
	
	private PowerSearchCondition searchCondition;
	
	private Operators merchant;
	
	@Autowired
	IorgService orgService;
	
	@Autowired
	IPagenitionService pagenitionService;
	
	@Autowired 
	IMerchantServices merchantServices;
	
	@Action(value = "queryMerchant", results = { @Result(name = "success", location = "/power/merchantList.jsp")
             })
	public String queryMerchantAction() throws Exception{
		
		//查询所有的机构
		org();
		
		return SUCCESS;
	}
	
	@Action(value = "queryMerchantList", results = { @Result(name = "success", location = "/power/merchantList.jsp")
           })
	//查询操作员
	public String queryMerchantListAction() throws Exception{
		
		//查询所有的机构
		//org();
		
        Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		if(searchCondition==null){
			searchCondition=(PowerSearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new PowerSearchCondition();
			}
		}
		try {
			if(Constance.MERCHANT_TYPE_DAILI.equals(logingMerchant.getRoleType())){
				//searchCondition.setSuperiorId(logingMerchant.getId());
				searchCondition.setMerType(Constance.MERCHANT_TYPE_DAILI);
				List<Operators> mList=merchantServices.listAllSubMerchants(logingMerchant.getId());
				searchCondition.setMerchantNos(dealSomeData(mList));
				//System.out.println(searchCondition.getFullSearchHQL(null));
				
			}
			org();
			//this.setCurrentPage(this.checkCurrentPage());
			int rows=pagenitionService.count(searchCondition);
			searchRsList=pagenitionService.findAll(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			if(searchRsList!=null&&searchRsList.size()>0){
				List<Object> tempList=new ArrayList<Object>();
				Map<String, Operators> mapMerchant=merchantServices.listAllMerchants(logingMerchant.getRoleType(), logingMerchant.getId(),logingMerchant.getOrgCode());
				for(Object o:searchRsList){
					Operators m=(Operators)o;
					if(mapMerchant.get(m.getSuperiorId()+"")==null){
					 m.setSuperMerchant(new Operators());
					}else {
						m.setSuperMerchant(mapMerchant.get(m.getSuperiorId()+""));
					}
					m.setMerLevelDesc(ConfigProperties.getAgentType(m.getAgentType()));
					tempList.add(m);
				}
				searchRsList.clear();
				searchRsList=tempList;
			}
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			
		} catch (ServiceException e) {
			
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			
		}
		
		return SUCCESS;
	}
	
	@Action(value = "queryPower", results = { @Result(name = "success", location = "/power/power.jsp")
            })
	//查询权限
	public String queryPowerAction(){
		//查询操作员所拥有的权限
		List<MerchantModuleRight> moduleList=new ArrayList<MerchantModuleRight>();
		
		//查询该操作员所该拥有的权限
		List<Module> moduleCateList=new ArrayList<Module>();
		
		try {
			moduleList=merchantServices.queryMerchantPowerByNo(merchant.getAccountNo());
			Operators mer=new Operators();
			mer.setAccountNo(merchant.getAccountNo());
			Operators merchant=merchantServices.login(mer);
			moduleCateList=merchantServices.queryModuleType(merchant.getRoleType());
			
			getRequest().setAttribute("moduleList", moduleList);
			getRequest().setAttribute("moduleCateList", moduleCateList);
			getRequest().setAttribute("accountNo", merchant.getAccountNo());
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		return SUCCESS;
	}
	
	@Action(value = "editMerchantPower", results = { @Result(name = "success", location = "/power/merchantList.jsp")
             })
	//修改操作员权限
	public String editMerchantPowerAction() throws Exception{
				//获取操作员的ID
				String accountNo=merchant.getAccountNo();
				//获取操作员新的权限
				String check=getRequest().getParameter("checkList");
				String[] list=null;
				list=check.split(",");
				
				//调用service层
				try {
					Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
					merchantServices.editUpdateMerchantPower(accountNo, list,logingMerchant);
					logger.info("------------------------------修改操作员权限成功！-----------------------------------");
				} catch (ServiceException e) {
					logger.info("------------------------------修改操作员权限失败！-----------------------------------");
					logger.error(e.getMessage(),e);
					return ERROR;
				}
				return queryMerchantListAction();
	}
	
	//查询机构
	public void org() throws Exception{
		Operators loginMerchant = (Operators) ActionContext.getContext().getSession().get(Constant.SESSION_LOGIN_MERCHANT);
		    List orgList=new ArrayList();
			
			Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			if(Constance.MERCHANT_TYPE_DAILI.equals(logingMerchant.getRoleType())){
				OrgBean org = new OrgBean();
				org=orgService.queryOrgByCode(logingMerchant.getOrgCode());
				orgList.add(org);
			}else{
				orgList=orgService.queryOrgList();
			}
			
			getRequest().setAttribute("orgList", orgList);
			
			Map<String, String> merLevels=ConfigProperties.getAgentTypeProperties();
			getRequest().setAttribute("merLevels", merLevels);
		
	}
	private String[] dealSomeData(List<Operators> list){
		String[] str=null;
		if(list!=null&&list.size()>0){
			str=new String[list.size()];
			for(int i=0;i<list.size();i++){
				str[i]=list.get(i).getAccountNo();
			}
		}
		return str;
	}
	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE+"";
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#getSearchConditionFromSession()
	 */
	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (PowerSearchCondition)getSession().getAttribute(SEARCH_SESSION_BEAN_MERCHANT_POWER);
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#getSearchConditionFromSubClass()
	 */
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#setSearchConditionToSubClass(com.roc.page.BaseSearchCondition)
	 */
	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#setSearchToConditionSession(com.roc.page.BaseSearchCondition)
	 */
	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_BEAN_MERCHANT_POWER, searchCondition);
	}

	public PowerSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(PowerSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public Operators getMerchant() {
		return merchant;
	}

	public void setMerchant(Operators merchant) {
		this.merchant = merchant;
	}


}
